import React, { useEffect, useRef, useState } from 'react';
import { Popconfirm, message, Form, Input, Tooltip } from 'antd';
import NewPageTemp from '@/template/newPageTemp';
import IrrSearchForm from '@/components/IrrSearchForm';
import IrrButton from '@/components/IrrButton';
import IrrActionOpt from '@/components/IrrActionOpt';
import IrrFormList from '@/components/IrrFormList';
import IrrModal from '@/components/IrrModal';

import { renderMoreActions } from '@/utils';
import { useSelector } from 'react-redux';

import './index.less';

interface Props {}
const refObj: any = {};
const valuesObj: any = {};
let pointNameList: any = [];
let curOuterIndex: number = -1;
const PatrolPlan: React.FC<Props> = (props) => {
  const pageRef = useRef<any>(null);
  const pointRef = useRef<any>(null);
  const rangeAddRef = useRef<any>(null);
  const irrModalRef = useRef<any>(null);
  // const batchRefList = useRef<any>(null);
  // const batchRefList = useRef<any[]>([]);
  const [pageStatus, setPageStatus] = useState<string>('');
  const [pageRange, setPageRange] = useState<string>('');
  const [nameList, setNameList] = useState<any[]>([]);
  const [dataList, setDataList] = useState<any[]>([]);
  const [outerIndex, setOuterIndex] = useState<number>(0);
  const [count, setCount] = useState<number>(5);
  const [searchList] = useState<any[]>([
    {
      renderType: 'input',
      title: '点位名称',
      dataIndex: 'pointName',
      paramsType: 'body',
    },
  ]);
  const [requestPage] = useState<any>({
    api: '',
    requestType: 'POST',
  });
  const [paramsPage, setParamsPage] = useState<any>({});
  const [initParams, setInitParams] = useState<any>({});
  const [mapOption, setMapOption] = useState<any>({});
  //   const { areaTreeData = [] } = useSelector((state: any) => {
  //     return {
  //       areaTreeData: state.areaTreeData,
  //     };
  //   });
  const tempSingleList = [
    {
      title: '点位名称',
      dataIndex: 'pointName',
      required: true,
      renderType: 'input',
      extra: {
        maxLength: 8,
      },
    },
    {
      title: '所属区域',
      dataIndex: 'pointArea',
      required: true,
      renderType: 'treeSelect',
      dataSource: [],
      extra: {
        onChange: (e: string) => {
          handleArea(e);
        },
      },
    },
    {
      title: '详细地址',
      dataIndex: 'pointAddress',
      required: true,
      renderType: 'input',
      extra: {
        maxLength: 30,
      },
    },
    {
      title: '坐标点',
      dataIndex: 'location',
      renderType: 'location',
      checkLocation: 'pointArea',
      required: true,
      extra: {
        disabled: false,
      },
      // everyItemStyle: { width: '380px', marginRight: '0' }
    },
    {
      renderType: 'uploadImage',
      title: '照片信息',
      dataIndex: 'imagePath',
      required: false,
    },
  ];
  const handleName = (rules: any, value: any, cb?: Function) => {
    if (value) {
      // const index = nameList.findIndex((item: any, index: number) => {
      //     return index !== curOuterIndex && item === value;
      // });
      const curNameList = [...pointNameList];
      curNameList[curOuterIndex] = '';
      if (curNameList.includes(value) && pointNameList.length > 0) {
        cb && cb('点位名称不能重复');
        return;
      }
    } else {
      cb && cb();
    }
  };
  const tempFormList = [
    {
      title: '点位名称',
      dataIndex: 'pointName',
      required: true,
      renderType: 'input',
      extra: {
        maxLength: 8,
      },
    },
    {
      title: '所属区域',
      dataIndex: 'pointArea',
      required: true,
      renderType: 'treeSelect',
      dataSource: [],
      extra: {
        onChange: (e: string) => {
          // handleArea(e);
        },
      },
    },
    {
      title: '详细地址',
      dataIndex: 'pointAddress',
      required: true,
      renderType: 'input',
      extra: {
        maxLength: 30,
      },
    },
    {
      title: '坐标点',
      dataIndex: 'location',
      renderType: 'location',
      checkLocation: 'pointArea',
      required: true,
      extra: {
        disabled: false,
      },
      everyItemStyle: { width: '380px', marginRight: '0' },
    },
    {
      renderType: 'uploadImage',
      title: '照片信息',
      dataIndex: 'imagePath',
      required: false,
    },
  ];
  const [formList, setFormList] = useState<any[]>([...tempSingleList]);

  const [itemFormList, setItemFormList] = useState<any>([
    tempFormList,
    tempFormList,
    tempFormList,
    tempFormList,
    tempFormList,
  ]);

  const [selectedRowKeys, setSelectedRowKeys] = useState<any>([]);
  const [selectedRows, setSelectedRows] = useState<any>([]);
  const [currentRecord, setCurrentRecord] = useState<any>({});

  const onFormListSubmit = (values: any) => {
    const curValues: any = {};
    for (let i in values) {
      if (values[i]) {
        curValues[i] = values[i];
      }
    }
  };

  const validateFinishSubmit = (values: any) => {
    const api: string =
      pageStatus === 'add' ? 'saveSinglePoint' : 'updateSinglePoint';
    const body = {
      ...values,
    };

    if (body.location) {
      body.longitude = body.location.split(',')[0];
      body.latitude = body.location.split(',')[1];
      if (body.hasOwnProperty('location')) {
        delete body.location;
      }
    }
    if (currentRecord.id) {
      body.id = currentRecord.id;
    }
    IrrbaseData[api]({
      body,
    })
      .then((res: IrrResponse) => {
        if (res.code !== 0) {
          message.warning(res.msg);
          return;
        }
        message.success(res.msg);
        pageRef?.current?.queryTableData(1, paramsPage);
        // this.formModalRef.close();
        pointSingleCancel();
      })
      .catch((err: IrrResponse) => {
        message.warning(err.msg);
      });
  };

  const handleArea = (item: string) => {
    const tempCurrentRecord = { ...currentRecord };
    if (item) {
      tempCurrentRecord.longitude = '';
      tempCurrentRecord.latitude = '';
      setCurrentRecord(tempCurrentRecord);
    }
    pointRef?.current.customSetForm({ location: '' });
  };
  const pointRangeCancel = () => {
    pointRef?.current?.resetFields();
    setPageRange('');
  };
  const pointRangeConfirm = () => {
    rangeAddRef?.current?.validateFields().then(() => {
      const values = rangeAddRef?.current?.getFieldsValue(true);
      // cb && cb(values);
      // pointRangeCancel();
      setInstance(values);
    });
  };

  const setInstance = (curValues: any) => {
    let api = 'savePointDistance';

    IrrbaseData[api]({
      body: `${curValues.id}`,
    })

      .then((res: IotResponse) => {
        if (res.code !== 0) {
          message.warning(res.msg);
          return;
        } else {
          pointRangeCancel();
          message.success(res.msg);
          pageRef?.current?.queryTableData(1, paramsPage);
        }
      })
      .catch((err: IrrResponse) => {
        message.warning(err.msg);
      });
  };

  const pointSingleCancel = () => {
    pointRef?.current?.resetForm();
    setPageStatus('');
  };
  const pointSingleConfirm = () => {
    pointRef?.current?.customValidate(validateFinishSubmit);
  };
  const pointBatchCancel = () => {
    for (let index = 0; index < count; index++) {
      refObj[index].current?.resetForm();
    }
    setPageStatus('');
    const tempItemFormList = [
      tempFormList,
      tempFormList,
      tempFormList,
      tempFormList,
      tempFormList,
    ];
    const number = tempItemFormList.length;
    setItemFormList(tempItemFormList);
    setCount(number);
  };
  const pointBatchConfirm = () => {
    const curList = [...dataList];
    if (curList.length === 0) {
      refObj[0].current?.customValidate();
      return;
    }
    const requireNum = ['pointName', 'pointArea', 'pointAddress', 'location'];
    let isFinish = true;
    curList.map((everyList: any, index: number) => {
      let intersection = [];
      for (let i in everyList) {
        if (everyList[i]) {
          for (let j = 0; j < requireNum.length - 1; j++) {
            if (i === requireNum[j]) {
              intersection.push(j);
            }
          }
        }
      }
      if (intersection.length < 3) {
        isFinish = false;
        if (intersection.length === 0) {
          refObj[index].current?.resetFormFields();
        } else {
          refObj[index].current?.customValidate();
        }
      }
    });
    //@ts-ignore
    const curName = [...new Set(nameList)];
    if (isFinish && curName.length === nameList.length) {
      lastHandleData(curList);
    }

    return;
  };

  const pointsBatchValidate = (values: any, curIndex: number) => {
    const requireNum = ['pointName', 'pointArea', 'pointAddress', 'location'];
    const curValues: any = {};
    let intersection = [];
    for (let i in values) {
      if (values[i]) {
        for (let j = 0; j < requireNum.length - 1; j++) {
          if (i === requireNum[j]) {
            intersection.push(j);
          }
        }
        curValues[i] = values[i];
      } else {
        curValues[i] = '';
      }
    }

    if (Object.keys(curValues).length) {
      valuesObj[curIndex] = curValues;
    }

    if (intersection.length > 3) {
      // console.log('x1', '校验成功');
    } else if (intersection.length < 3 && intersection.length > 0) {
      refObj[curIndex].current?.customValidate();
      return;
    }
    if (intersection.length === 0 && curIndex !== count - 1) {
      refObj[curIndex].current?.resetFormFields();
      // refObj[0].current?.customValidate();
      return;
    }
    if (curIndex === count - 1) {
      if (!Object.keys(valuesObj).length) {
        if (!Object.values(valuesObj).filter(Boolean).length) {
          refObj[0].current?.customValidate();
        }

        return;
      }
      // lastHandleData();
    }
  };

  const lastHandleData = (list: any) => {
    const curlist = [];
    for (let i in list) {
      const temp = { ...list[i] };
      temp.longitude = temp?.location?.split(',')[0];
      temp.latitude = temp?.location?.split(',')[1];
      if (temp.hasOwnProperty('location')) {
        delete temp.location;
      }
      curlist.push(temp);
    }

    IrrbaseData.batchSavePoint({
      body: curlist,
    })
      .then((res: any) => {
        if (res.code === 0) {
          message.success('批量新增成功');
          pointBatchCancel();
          pageRef?.current?.queryTableData(1, paramsPage);
        } else {
          message.warning(res.msg);
        }
      })
      .catch((res: any) => {
        message.warning(res.msg);
      });
  };

  const onFormListChange = (
    curVal: any,
    totolVal: any,
    changeType?: string,
  ) => {
    // console.log('x1', curVal, '111', totolVal, 'ccc', changeType);
  };

  const resetFormList = () => {
    // initData(1, {}, 'query');
  };

  const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
    setSelectedRowKeys([...selectedRowKeys]);
    setSelectedRows([...selectedRows]);
  };

  const columns = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'curIndex',
      key: 'curIndex',
      width: '100px',
      render: (text: any, record: anyObject, index: number) => {
        return <span className="diaplay_two_cell">{index + 1}</span>;
      },
    },
    {
      title: '点位名称',
      align: 'center',
      dataIndex: 'pointName',
      key: 'pointName',
    },
    {
      title: '所属区域',
      align: 'center',
      key: 'pointAreaName',
      dataIndex: 'pointAreaName',
      extra: {
        onChange: (e: string) => {
          // handleTreeArea(e);
        },
      },
    },
    {
      title: '坐标点',
      align: 'center',
      dataIndex: 'longitude',
      key: 'longitude',
      render: (text: any, record: anyObject) => {
        if (record.latitude && record.latitude) {
          return (
            <span>
              {record.latitude},{record.longitude}
            </span>
          );
        }
        return <span>--</span>;
      },
    },
    {
      title: '详细地址',
      align: 'center',
      dataIndex: 'pointAddress',
      key: 'pointAddress',
    },

    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      align: 'center',
      width: 300,
      render: (text: any, record: anyObject, index: number) => {
        const actionsList = [
          <span
            key={1}
            onClick={() => {
              //
              handlePointAction('view', record);
            }}
          >
            查看
          </span>,
          <span
            key={2}
            onClick={() => {
              //
              handlePointAction('edit', record);
            }}
          >
            编辑
          </span>,
          <Popconfirm
            key={3}
            title={'您确定删除该点位信息吗'}
            okText="确认"
            cancelText="取消"
            onConfirm={() => {
              deletePointRecord(record.id);
            }}
          >
            <span className="group_action_delete">删除</span>
          </Popconfirm>,
        ];
        return (
          <div className="table_group--action">
            {renderMoreActions(actionsList)}
          </div>
        );
      },
    },
  ];

  const deletePointRecord = (id: string) => {
    IrrbaseData.deleteSinglePoint({
      body: `${id}`,
    })
      .then((res: any) => {
        if (res.code === 0) {
          message.success('删除成功');
          pageRef?.current?.queryTableData(1, paramsPage);
        } else {
          message.warning(res.msg);
        }
      })
      .catch((res: any) => {
        message.warning(res.msg);
      });
  };

  const handlePointAction = (pageStatus: string, currentRecord?: any) => {
    setPageStatus(pageStatus);
    const tempCurObj = { ...currentRecord };
    if (currentRecord?.longitude && currentRecord?.latitude) {
      tempCurObj.location = `${currentRecord.longitude},${currentRecord.latitude}`;
    }
    tempCurObj?.id ? setCurrentRecord(tempCurObj) : setCurrentRecord({});
    if ('view' === pageStatus || 'edit' === pageStatus) {
      const curMapOption = {
        areaId: currentRecord.pointArea,
        name: currentRecord.pointArea,
        readonly: true,
      };
      const curFormList = [...formList];
      curFormList[1].disabled = true;
      //   curFormList[1].dataSource = [...areaTreeData];
      setFormList(curFormList);
      setMapOption(curMapOption);
    } else if ('add' === pageStatus) {
      const curFormList = [...formList];
      curFormList[1].disabled = false;
      //   curFormList[1].dataSource = [...areaTreeData];
      setFormList(curFormList);
    } else if ('batchAdd' === pageStatus) {
      const tempBatchList = [...itemFormList];
      tempBatchList.map((item: any, index: number) => {
        // item[1].dataSource = [...areaTreeData];
        item[0].customValidator = {
          flag: true,
          handleValidator: [
            { required: true, message: '请输入点位名称' },
            { validator: handleName },
          ],
        };
        return item;
      });
      setItemFormList(tempBatchList);
    }
  };
  const handleRangeAdd = (pageStatus: string) => {
    setPageRange(pageStatus);
  };
  useEffect(() => {
    if (pageRange === 'rangeAdd') {
      irrModalRef?.current?.customOpen(getPointDistance);
    }
  }, [pageRange]);

  const getPointDistance = (curValues: any) => {
    let api = 'getPointDistance';
    // IrrbaseData[api]({})

    //   .then((res: IotResponse) => {
    //     if (res.code !== 0) {
    //       // message.warning(res.msg);
    //       return;
    //     } else {
    //       rangeAddRef?.current?.setFieldsValue({
    //         id: res.data,
    //       });
    //     }
    //   })
    //   .catch((err: IrrResponse) => {
    //     // message.warning(err.msg);
    //   });
  };
  useEffect(() => {
    if (currentRecord?.id && ('view' === pageStatus || 'edit' === pageStatus)) {
      pointRef.current.customSetForm(currentRecord);
    }
  }, [pageStatus, currentRecord]);

  const onSearchSubmit = (values: any) => {
    const curValues: any = {};
    for (let i in values) {
      if (values[i]) {
        curValues[i] = values[i];
      }
    }
    const paramsObj = { ...curValues };
    setParamsPage(paramsObj);
    pageRef?.current?.queryTableData(1, paramsObj);
  };

  const onSearchChange = () => {};

  const resetHandleBtn = (values: any = {}) => {
    let paramsObj = { ...initParams };
    setParamsPage(paramsObj);
    pageRef?.current?.queryTableData(1, paramsObj);
  };

  const startAdd = () => {};

  const afterSetLocation = (item: string) => {
    const tempCurrentRecord = { ...currentRecord };
    if (item) {
      tempCurrentRecord.longitude = item.split(',')[0];
      tempCurrentRecord.latitude = item.split(',')[1];
      setCurrentRecord(tempCurrentRecord);
    }
  };

  const actionsBtn = [
    <IrrButton
      key="1"
      onClick={() => {
        handlePointAction('add');
      }}
    >
      新增
    </IrrButton>,
    <IrrButton
      key="2"
      onClick={() => {
        curOuterIndex = -1;
        pointNameList = [];
        setDataList([]);
        handlePointAction('batchAdd');
      }}
    >
      批量新增点位
    </IrrButton>,
    <IrrButton
      key="3"
      onClick={() => {
        handleRangeAdd('rangeAdd');
      }}
    >
      点位有效范围配置
    </IrrButton>,
  ];

  const batchFormBtn = [
    <IrrButton
      style={{ display: 'inline-block' }}
      disabled={count > 99}
      onClick={() => {
        handleBatchAddAction();
      }}
    >
      添加一组数据
    </IrrButton>,
  ];

  const handleBatchAddAction = () => {
    const tempItemFormList = [...itemFormList];
    const number = tempItemFormList.length;
    const singleList: any = [...tempFormList];
    // singleList[1].dataSource = [...areaTreeData];
    singleList[0].customValidator = {
      flag: true,
      handleValidator: [
        { required: true, message: '请输入点位名称' },
        { validator: handleName },
      ],
    };
    tempItemFormList.push(singleList);
    setItemFormList(tempItemFormList);
    setCount(number + 1);
  };
  const batchFormListChange = (
    curVal: any,
    totolVal: any,
    curIndex: number,
  ) => {
    setOuterIndex(curIndex);
    curOuterIndex = curIndex;
    if (curVal.hasOwnProperty('pointName')) {
      const tempNameList = [...nameList];
      tempNameList[curIndex] = curVal['pointName'];
      pointNameList[curIndex] = curVal['pointName'];
      setNameList(tempNameList);
    }
    const curObj: any = {};
    Object.keys(totolVal).map((item: any, index: number) => {
      curObj[item] = totolVal[item] || '';
    });
    const tempDataList = [...dataList];
    tempDataList[curIndex] = curObj;
    setDataList(tempDataList);
  };
  const handleLocation = (locations: any, preIndex: number) => {
    if (locations) {
      const tempDataList = [...dataList];
      if (tempDataList[preIndex])
        tempDataList[preIndex]['location'] = locations;
      setDataList(tempDataList);
    }
  };

  const handleCurRef = (curRef: any, curIndex: number) => {
    refObj[curIndex] = curRef;
  };
  return (
    <>
      {pageStatus && pageStatus !== 'batchAdd' ? (
        <IrrActionOpt
          title={'西稚嫩'}
          onPointCancel={pointSingleCancel}
          onPointConfirm={pointSingleConfirm}
          containterClass={'points_single_add__form'}
          pageStatus={pageStatus}
        >
          <IrrFormList
            formList={formList}
            layout="vertical"
            ref={pointRef}
            onFormListSubmit={onFormListSubmit}
            currentRecord={currentRecord}
            mapOption={mapOption}
            formDisabled={pageStatus === 'view'}
            onFormListChange={onFormListChange}
            resetFormList={resetFormList}
            afterSetLocation={afterSetLocation}
            customFooter={true}
          />
        </IrrActionOpt>
      ) : null}
      {pageRange && pageRange === 'rangeAdd' && (
        <IrrModal
          title={'xxxxxxxxx'}
          ref={irrModalRef}
          width={'550px'}
          maskClosable={true}
          className={`check_modal__containter__submit`}
          transCancel={pointRangeCancel}
          transConfirm={pointRangeConfirm}
        >
          <div className="point-form_range_add">
            <Form ref={rangeAddRef} autoComplete="off">
              <div className="point-form_range_add__box">
                <Form.Item
                  label="有效范围："
                  name="id"
                  rules={[
                    {
                      required: true,
                      message: '输入的数字不能小于等于0，不能超过1000',
                    },
                    {
                      pattern: /^([1-9][0-9]{0,2}|1000)(\.\d)?$/,
                      message:
                        '输入的数字不能小于1，不能超过1000，且只能输入一位小数',
                    },
                  ]}
                >
                  <Input placeholder="请输入数值" />
                </Form.Item>
                <div className="point-form_range_add__desc">
                  <Tooltip
                    placement="right"
                    title={
                      '为了保证巡查执行的有效性，在每次执行巡查时，系统使用小程序的定位坐标与规定的点位坐标进行比对，两者距离超出某个值时，小程序会对执行人员进行提醒，不能继续执行巡查任务。'
                    }
                  >
                    (单位：米)
                  </Tooltip>
                </div>
              </div>
            </Form>
          </div>
        </IrrModal>
      )}
      <NewPageTemp
        ref={pageRef}
        actionsGroup={actionsBtn}
        requestPage={requestPage}
        paramsPage={paramsPage}
        columns={columns}
        // rowSelection={{ selectedRowKeys, onChange: onSelectChange, type: 'checkout' }}
        title={'点位管理'}
        treeOption={{
          areaKey: 'pointArea',
        }}
      >
        <IrrSearchForm
          searchList={searchList}
          key="custom"
          onSearchSubmit={onSearchSubmit}
          onValuesChange={onSearchChange}
          resetTrans={resetHandleBtn}
        />
      </NewPageTemp>
    </>
  );
};

export default PatrolPlan;
